package com.ying.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * ClassName: SimpleConsumer
 * Package: com.ying
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/3/23 19:18
 * @Version 1.0
 */
public class SimpleConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("192.168.160.134");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("myHV");
        connectionFactory.setUsername("testUser");
        connectionFactory.setPassword("123456");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        //声明channel,防止消费先启动没有channel报错
        channel.queueDeclare("hello",true,false,false,null);

        //4.接收队列中的消息
        /**
         * queue – 队列名称
         * autoAck
         *       true 接收到传递过来的消息后acknowledged（自动告诉RabbitMQ已收到）
         *       false 接收到消息后不应答服务器
         * callback – 消费者对象回调的接口,收到消息后会执行回调对象中的方法
         */
        channel.basicConsume("hello",true,new DefaultConsumer(channel){
            /**
             *
             consumerTag – 与消费者相关联的唯一标识
             envelope – 获取交换机信息,routing key等信息
             properties –  获取信息相关的属性,AMQP.BasicProperties
             body – 消息内容
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(consumerTag);
                System.out.println(envelope.getExchange() + " " + envelope.getRoutingKey());
                System.out.println(properties);
                System.out.println(new String(body));
            }
        });

    }
}
